package com.youzan.cloud.utils;

import com.youzan.cloud.common.exception.AuthenticationFailExcetion;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * @author tangsen233
 * @version 1.0
 * @description: TODO
 * @date 2021/12/13 19:00
 */

public class SignUtil {

    /**
     * @description:  HAS256Hmac加密生成sign
     * @param  message 拼接的参数
     * @param  secret 加密的密钥
     * @return sign 生成的签名
     * @version 1.0
     */
    public static String encryptSHA256Hmac(String message, String secret) {
        if(message==null || secret==null)
        {
            return null;
        }
        try {
            Mac sha256Hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
            sha256Hmac.init(secretKey);
            byte[] bytes = sha256Hmac.doFinal(message.getBytes("UTF-8"));
            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(bytes);
        } catch (Exception e) {
            throw new AuthenticationFailExcetion("生成sign签名异常");
        }
    }
}